package com.zrrd.learn.chapter08.reflex;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 狮子
 *
 * @author asus
 * @version 1.0
 * @date 2023/8/8 13:27
 */
public class HomeWorkLion {

    public  Lion getLionInstance(String name,String color) {
        //反射
        Class<Lion> l1 = Lion.class;
        Lion mylion = null;
        try {

            //反射得到的实例对象l1
            mylion = l1.newInstance();

            //获取方法名字叫setName,参数为String.class,返回一个关联对象。
            Method setNameMethod = l1.getDeclaredMethod("setName",String.class);
            setNameMethod.invoke(mylion,name);

            // 上述两行代码意义等同于： mylion.setName(name);

            Method setColorMethod = l1.getDeclaredMethod("setColor",String.class);
            setColorMethod.invoke(mylion,color);



        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e)
        {
           throw new RuntimeException(e);
        }
        return  mylion;
    }

    public static void main(String[] args) {
            HomeWorkLion hm1 = new HomeWorkLion();
            Lion l = hm1.getLionInstance("辛巴","红色");

        System.out.println(l.getName());
        System.out.println(l.getColor());
    }


}
